import Redis from 'ioredis';
import { config } from './index';

// Redis连接配置
const redisConfig = {
  host: config.redis.host,
  port: config.redis.port,
  ...(config.redis.password && { password: config.redis.password }),
  db: config.redis.db,
  retryDelayOnFailover: config.redis.retryDelayOnFailover,
  maxRetriesPerRequest: config.redis.maxRetriesPerRequest,
  
  // 连接选项
  connectTimeout: 10000,
  lazyConnect: true,
  keepAlive: 30000,
  
  // 重试策略
  retryStrategy: (times: number) => {
    const delay = Math.min(times * 50, 2000);
    return delay;
  },
  
  // 重连策略
  reconnectOnError: (err: Error) => {
    const targetError = 'READONLY';
    return err.message.includes(targetError);
  },
};

// 创建Redis客户端
export const redis = new Redis(redisConfig);

// Redis事件监听
redis.on('connect', () => {
  console.log('Redis client connected');
});

redis.on('ready', () => {
  console.log('Redis client ready');
});

redis.on('error', (err) => {
  console.error('Redis client error:', err);
});

redis.on('close', () => {
  console.log('Redis client connection closed');
});

redis.on('reconnecting', () => {
  console.log('Redis client reconnecting...');
});

// Redis连接测试
export const testRedisConnection = async (): Promise<boolean> => {
  try {
    await redis.ping();
    console.log('Redis connection test successful');
    return true;
  } catch (error) {
    console.error('Redis connection test failed:', error);
    return false;
  }
};

// 获取Redis客户端实例
export const getRedisClient = (): Redis => {
  return redis;
};

// 优雅关闭Redis连接
export const closeRedis = async (): Promise<void> => {
  try {
    await redis.quit();
    console.log('Redis connection closed');
  } catch (error) {
    console.error('Error closing Redis connection:', error);
  }
};

export default redis;